package experiment.dao;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import experiment.model.UserPOJO;


@Repository
public class UserDaoImpl implements UserDao{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public Boolean selectByMap(UserPOJO user) {
		UserPOJO result;
		if(user.getPassword() != null && user.getPassword()!="") {
			String sql = "select * from users where email = ? and password = ?";
			try {
				result = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<UserPOJO>(UserPOJO.class),user.getEmail(), user.getPassword());
			}catch(Exception e) {
				return false;
			}
		} else {
			String sql = "select * from users where email = ? ";
			try {
				result = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<UserPOJO>(UserPOJO.class), user.getEmail());
			}catch(Exception e) {
				return false;
			}
		}
		
		return true;
	}
	
	public void insert(UserPOJO user) {
		String sql = "insert into users (user_name, password, phone_number, email)  values(?,?,?,?)";
		jdbcTemplate.update(sql, user.getUserName(), user.getPassword(),user.getPhone(), user.getEmail());
	}
	
	public Boolean hasPermission(String email) {
		String sql = "select count(*) from users where email = ? and is_vip = 1";
		int result = jdbcTemplate.queryForObject(sql, Integer.class, email);
		return 1 == result;
	}
	
}
